package com.leyou.user.web;


import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.UserContext;
import com.leyou.user.dto.UserDto;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


@RestController
@RequestMapping("info")
public class UserController {
    private UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 校验手机号或用户名是否存在
     * @param data 用户名或手机号
     * @param type 数据类型：1是用户名；2是手机；其它是参数有误
     * @return true：可以使用; false：不可使用
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> exists(@PathVariable("data") String data, @PathVariable("type") Integer type) {
        return ResponseEntity.ok(userService.exists(data, type));
    }

    @GetMapping("/")
    public ResponseEntity<UserDto> queryByNameAndPd(@RequestParam("username") String username, @RequestParam("password") String password) {
        return ResponseEntity.ok(userService.queryByNameAndPd(username, password));
    }

    @PostMapping("/")
    public ResponseEntity<Void> saveUser(@Valid User user, @RequestParam("code") String code) {
        userService.saveUser(user,code);
        return ResponseEntity.ok().build();
    }


    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone")String phone) {
        userService.sendCode(phone);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/me")
    public ResponseEntity<UserDetail> checkLogin(@CookieValue("LY_TOKEN")String token){
        return ResponseEntity.ok(UserContext.getUser());
    }

}
